<script setup lang="ts">
  import { computed, onMounted, ref } from 'vue';
  import { TableProps } from 'ant-design-vue';
  import { Devices, exportAllDeviceApi, selectDeviceListApi } from '@/api/hc/device';
  import { Persistent } from '@/utils/cache/persistent';
  import { SN_KEY } from '@/enums/cacheEnum';
  import { router } from '@/router';
  import { PageWrapper } from '@/components/Page';

  const pageSize = ref<number>(10);
  const snStr = ref<string>('');
  const pageNum = ref<number>(1);
  const total = ref<number>(0);
  const pagination = computed(() => ({
    total: total.value,
    current: pageNum.value,
    pageSize: pageSize.value,
  }));

  onMounted(() => {
    selectDeviceList();
  });

  const deviceColumns = [
    {
      title: 'deviceName',
      dataIndex: 'deviceName',
      key: 'deviceName',
    },
    {
      title: 'id',
      dataIndex: 'id',
      key: 'id',
    },
    {
      title: 'sn',
      dataIndex: 'sn',
      key: 'sn',
    },
    {
      title: 'pn',
      dataIndex: 'pn',
      key: 'pn',
    },
    {
      title: 'deviceStatus',
      dataIndex: 'deviceStatus',
      key: 'deviceStatus',
    },
    {
      title: 'Action',
      key: 'action',
    },
  ];
  const deviceList = ref<Devices[]>([]);

  const handleTableChange: TableProps['onChange'] = (pag: {
    pageSize: number;
    current: number;
  }) => {
    // pageSize.value = pag.pageSize;
    pageNum.value = pag?.current;
    selectDeviceList();
  };

  function selectDeviceList() {
    selectDeviceListApi({
      pageNum: pageNum.value,
      pageSize: pageSize.value,
      snStr: snStr.value,
    }).then((res) => {
      deviceList.value = res.list;
      total.value = res.total;
    });
  }

  function exportAll() {
    exportAllDeviceApi({
      createTimeStart: 0,
      createTimeEnd: new Date(),
    });
  }

  function clickItem(item: Devices) {
    console.log(item);
    Persistent.setLocal(SN_KEY, item.sn);
    router.push('/zhm/device');
  }
</script>

<template>
  <PageWrapper>
    <a-space>
      <a-button type="primary" danger @click="exportAll">导出全部</a-button>
      <a-input v-model:value="snStr" />
      <a-button type="primary" @click="selectDeviceList">查询</a-button>
    </a-space>

    <a-table
      :dataSource="deviceList"
      :columns="deviceColumns"
      :pagination="pagination"
      @change="handleTableChange"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <span>
            <a-divider type="vertical" />
            <a class="ant-dropdown-link" @click="clickItem(record)">
              详情
              <down-outlined />
            </a>
          </span>
        </template>
      </template>
    </a-table>
  </PageWrapper>
</template>

<style scoped lang="less"></style>
